package com.gec.system.config;

import com.gec.model.system.ITripUser;

import com.gec.system.filter.JwtAuthenticationFilter;
import com.gec.system.filter.JwtAuthorizationFilter;
import com.gec.system.service.ITripLoginLogService;
import com.gec.system.service.ITripMenuService;
import com.gec.system.service.ITripUserService;
import com.gec.system.utils.UserDetailImpl;
import com.gec.system.utils.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启注解功能，默认禁用注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Autowired
    private ITripUserService iTripUserService;

    @Autowired
    private ITripLoginLogService iTripLoginLogService;

    @Autowired
    private ITripMenuService iTripMenuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserDetailServiceImpl userDetailService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public UserDetailsService userDetailsService() {
        return userDetailService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());//直接调用上面这个方法
    }
    /**
     * 配置哪些请求不拦截
     * 排除swagger相关请求
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/favicon.ico","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html");
    }

    //springsecurity 主配置方法，链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()  //CrossOrigin跨域
                .and()

                .authorizeRequests()
                // 指定某些接口不需要通过验证即可访问。登陆接口肯定是不需要认证的
                .antMatchers("/system/upload/uploadImage").permitAll()
                .antMatchers("/system/upload/uploadVideo").permitAll()
                .antMatchers("/system/itrUser/register").permitAll()
                .antMatchers("/system/itrUser/checkOutName").permitAll()
                .antMatchers("/system/index/login")
                .permitAll()
                .anyRequest()
                .authenticated()   //表示 所有的请求资源都要被认证

                .and()
                .addFilter(new JwtAuthenticationFilter(authenticationManager(),redisTemplate,iTripLoginLogService)) //添加用户认证（登录）过程的过滤器
                .addFilterBefore(new JwtAuthorizationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class); //过滤请求判断身份（判断是否有jwt，jwt是否有效）
        http.csrf().disable();//如果不禁用，post提交的参数会被拦截
        //禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
